import {reqAddCartSuccess,reqShopCartList,reqShopCarState,reqDeleteCart} from '@/api'
//getAddCartSuccess的VUEX模块
//VUE中的四个核心概念
const state = {
    //存储数据
    shopCartList:[],
};
const mutations = {
    //直接修改数据
    RECEIVE_SHOPCARTLIST(state,shopCartList){
        state.shopCartList = shopCartList
    }
};
const actions = {
    //与组件当中的用户对接
    //一般是异步发送请求
    //提交mutations
    async getAddCartSuccess({commit},{skuId,skuNum}){
        const result =  await reqAddCartSuccess(skuId,skuNum);
        if(result.code === 200){
            return "ok"
        }else{
            return Promise.reject(new Error('failed'));
        }
    },
    //获取购物车列表的
    async getShopCartList({commit}){
        const result = await reqShopCartList();
        //后期出现假报错留意此处  (已解决)
        if(result.code === 200){
            let cartInfoList = []
            if(result.data.length){
                [{cartInfoList}] = result.data
            }
            commit("RECEIVE_SHOPCARTLIST",cartInfoList);
        }
    },
    //修改购物车状态的函数
    async getShopCarState({commit},{skuID,isChecked}){
        const result = await reqShopCarState(skuID,isChecked)
        if(result.code === 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'));
        }
            
    },
    //删除单个购物车的函数
    async deleteShopCar({commit},skuId){
        const result = await reqDeleteCart(skuId)
        if(result.code === 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'));
        }
    },
    //删除多个购物车的函数
    getDeleteShopCarAll({commit,dispatch}){
        let promises = [];
        this.state.addcartsuccess.shopCartList.forEach(item=>{
            if(item.isChecked === 1){
                let promise = dispatch("deleteShopCar",item.skuId);
                promises.push(promise);
            }
        })
        return Promise.all(promises)
    },
    //全选全不选的函数(通过多次调用单次修改状态的函数 getShopCarState)
    getShopCarStateAll({commit,dispatch},isChecked){
        let promises = []
        this.state.addcartsuccess.shopCartList.forEach(item=>{
            if(item.isChecked === isChecked) return;
            let promise = dispatch("getShopCarState",{skuID:item.skuId,isChecked});
            promises.push(promise);
        })
        return Promise.all(promises)
    }

};
const getters = {
    //后面用来简化数据的
}

export default{
    state,
    mutations,
    actions,
    getters,
};